import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'
import { agencyAsync } from '@/appox/appox'
import { useLanguageStore } from '@/stores/language'

export const useSessionEditorStore = defineStore('sessionEditor', () => {
  // 状态
  const dialogQueue = new DialogQueue()
  const session = ref(null)
  const startTime = ref('')
  const duration = ref('')
  const hostSync = ref(false)
  const comments = ref('')
  const properties = ref([])
  const currentRowIndex = ref(-1)
  const isRemoved = ref(false)

  // 计算属性
  const canRemoveProperties = computed(() => currentRowIndex.value >= 0)

  // 辅助函数
  function formatTimeLength(seconds) {
    const isChinese = useLanguageStore().isChinese

    if (seconds == null) {
      return isChinese ? "(未知)" : "(Unknown)"
    }
    
    if (seconds < 1) {
      return isChinese ? "0秒" : "0 sec"
    }
    
    const span = new Date(seconds * 1000)
    const days = Math.floor(seconds / (24 * 60 * 60))
    const hours = span.getUTCHours()
    const minutes = span.getUTCMinutes()
    const secondsRemain = span.getUTCSeconds()
    const ms = span.getUTCMilliseconds()
    
    let text = ""
    text += (days > 0 ? (days + (isChinese ? "天 " : " day ")) : "")
    text += (hours > 0 ? (hours + (isChinese ? "时 " : " hour ")) : "")
    text += (minutes > 0 ? (minutes + (isChinese ? "分 " : " min ")) : "")
    text += (secondsRemain > 0 ? (secondsRemain + (isChinese ? "秒 " : " sec ")) : "")
    text += (ms > 0 ? (ms + (isChinese ? "毫秒 " : " ms ")) : "")
    
    return text
  }

  // 动作
  async function loadSessionInfo() {
    if (!session.value) return

    const [localDate, length, hostSynced, comment, props] = await Promise.all([
      agencyAsync.getLocalDateTime(session.value, 0, false),
      agencyAsync.getSessionLength(session.value),
      agencyAsync.getSessionHostSync(session.value),
      agencyAsync.getSessionComment(session.value),
      agencyAsync.getSessionProperties(session.value)
    ])

    startTime.value = localDate.toString()
    duration.value = formatTimeLength(length)
    hostSync.value = hostSynced
    comments.value = comment
    properties.value = Object.entries(props).map(([key, value]) => ({ key, value }))
  }

  function addProperty(key = '', value = '') {
    properties.value.push({ key, value })
  }

  function removeCurrentProperty() {
    if (currentRowIndex.value >= 0 && currentRowIndex.value < properties.value.length) {
      properties.value.splice(currentRowIndex.value, 1)
      currentRowIndex.value = -1
    }
  }

  function setCurrentRow(index) {
    currentRowIndex.value = index
  }

  async function removeSession() {
    if (!isRemoved.value && await agencyAsync.removeSession(session.value, false)) {
      isRemoved.value = true
      hide()
    }
  }

  async function saveSession() {
    if (!session.value || isRemoved.value) return

    await agencyAsync.setSessionHostSync(session.value, hostSync.value)
    await agencyAsync.setSessionComment(session.value, comments.value)

    const props = {}
    properties.value.forEach(({ key, value }) => {
      const trimmedKey = key.trim()
      if (trimmedKey) {
        props[trimmedKey] = value.trim()
      }
    })
    await agencyAsync.setSessionProperties(session.value, props)
  }

  function show(sessionId) {
    return dialogQueue.show({
      onLoaded: async () => {
        session.value = sessionId
        isRemoved.value = false
        currentRowIndex.value = -1
        await loadSessionInfo()
      },
      onHidden: async () => {
        if (!isRemoved.value) {
          await saveSession()
        }
      }
    })
  }

  function hide() {
    dialogQueue.hide()
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    startTime,
    duration,
    hostSync,
    comments,
    properties,
    currentRowIndex,
    // 计算属性
    canRemoveProperties,
    // 动作
    addProperty,
    removeCurrentProperty,
    setCurrentRow,
    removeSession,
    show,
    hide,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
})